package com.wangxinenpu.springbootdemo.service.impl;

import com.wangxinenpu.springbootdemo.config.JwtTokenUtil;
import com.wangxinenpu.springbootdemo.config.security.JwtUser;
import com.wangxinenpu.springbootdemo.dataobject.model.LoginUser;
import com.wangxinenpu.springbootdemo.service.LoginService;
import com.wangxinenpu.springbootdemo.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private TokenService tokenService;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Override
    public String login(String username, String password) {
        String verifyKey = username;
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                log.error("异常",e);
            }
            else
            {
                log.error("异常",e);
            }
        }
        JwtUser loginUser = (JwtUser) authentication.getPrincipal();
        // 生成token
        return jwtTokenUtil.generateToken(loginUser);
    }
}
